<?php
namespace app\common\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use WeChatPay\Builder;
use app\common\service\wechat\WechatPay;

class DownloadWechatCert extends Command
{
    protected function configure()
    {
        $this->setName('download:wechat_cert')->setDescription('下载微信 V3 平台证书');
    }

    protected function execute(Input $input, Output $output)
    {
        $client = WechatPay::v3Client();
        $resp = $client->chain('v3/certificates')->get();
        $data = json_decode($resp->getBody(), true);
        foreach ($data['data'] as $item) {
            $serial = $item['serial_no'];
            $encryptCert = $item['encrypt_certificate'];
            $plain = \WeChatPay\Crypto\AesGcm::decrypt(
                $encryptCert['associated_data'],
                $encryptCert['nonce'],
                $encryptCert['ciphertext'],
                config('wechat.secret_key')
            );
            file_put_contents(root_path() . "cert/{$serial}.pem", $plain);
            $output->writeln("certificate {$serial} saved.");
        }
    }
}